﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Admintool.Infrastructure;

namespace Admintool
{
    partial class Program
    {

        [Command("encode uiid")]
        public static void EncodeUiid([Required(Description = "uiid to encode")]string uiid)
        {
            string orginalid = uiid;

            ConsoleHelper.ShowMessage("uiid:{0} , after encoding: {1}", ConsoleColor.Green, uiid, EncryptUIID(uiid));

        }


        [Command("encode uiid")]
        public static void DecodeUiid([Required(Description = "uiid to decode")]string uiid)
        {
            string plainid = string.Empty;
            uiid = uiid.Trim();
            bool valid = DecryptUIID(uiid, ref plainid);

            if (valid)
            {
                ConsoleHelper.ShowMessage("encrypted id :{0} ,after decoding : {1}",ConsoleColor.Green, uiid, plainid);
            }
            else
            {
                ConsoleHelper.ShowMessage("failed to decode!",ConsoleColor.Red);
            }

        }


        public static string EncryptUIID(string uiid)
        {
            if (!string.IsNullOrEmpty(uiid))
            {
                string md5uiid = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(uiid))).Replace("-", "").ToLower();
                string headPart = md5uiid.Substring(0, 4);
                string tailPart = md5uiid.Substring(md5uiid.Length - 4, 4);

                uiid = uiid.Insert(1, headPart);
                uiid = uiid.Insert(uiid.Length - 1, tailPart);

            }

            return uiid;
        }


        private static bool DecryptUIID(string uiid, ref string realUniqueID)
        {
            //c9f6e3c954a697f8a6328e4f520c86485f3654383dc08534b7fa81d5ddea81a6
            bool flag = false;
            if (!string.IsNullOrEmpty(uiid) && uiid.Length > 8)
            {
                string md5Tail = uiid.Substring(uiid.Length - 5, 4);
                string uniqueIDStep1 = uiid.Remove(uiid.Length - 5, 4);
                string md5Head = uniqueIDStep1.Substring(1, 4);
                string uniqueIDStep2 = uniqueIDStep1.Remove(1, 4);

                string md5String = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(uniqueIDStep2))).Replace("-", "").ToLower();
                if (string.Compare(md5Head, md5String.Substring(0, 4), true) == 0 && string.Compare(md5Tail, md5String.Substring(md5String.Length - 4, 4), true) == 0)
                {
                    realUniqueID = uniqueIDStep2;
                    flag = true;
                }
            }
            return flag;
        }



    
    
    }
}
